package model

type InviteServer interface {
	Create(invite *InviteList) (err error)
	GetInvited(openid string) (info []InviteInfo)
	GetInvited2(openid string) (info []InviteInfoImg)
	InviteCount(openId string) (count int)
	InviteCount20(openId string) (count int)
	Invited(openId string) (count int)
}

type inviteListServer struct {
}

func NewInviteServer() InviteServer {
	return &inviteListServer{}
}

func (u *inviteListServer) Create(invite *InviteList) (err error) {
	sql := "INSERT INTO invite_list (open_id, invite_openid, time) VALUES (?, ?, ?)"
	stmt, err := Db.Prepare(sql)
	if err != nil {
		return
	}
	defer stmt.Close()

	res, err := stmt.Exec(invite.OpenId, invite.InviteOpenId, invite.Time)
	if err != nil {
		return
	}
	id, err := res.LastInsertId()
	if err != nil {
		return
	}
	invite.Id = int(id)
	return nil
}

func (u *inviteListServer) Invited(openId string) (count int) {
	_ = Db.QueryRow("SELECT count(id) FROM invite_list WHERE invite_openid = ?", openId).Scan(&count)
	return
}

func (u *inviteListServer) InviteCount(openId string) (count int) {
	_ = Db.QueryRow("SELECT count(id) FROM `invite_list` WHERE open_id = ?", openId).Scan(&count)
	return
}

func (u *inviteListServer) InviteCount20(openId string) (count int) {
	_ = Db.QueryRow("SELECT count(invite_list.id) FROM `invite_list` inner join `users` on invite_list.invite_openid = users.unique_id WHERE invite_list.open_id = ? and users.levels >= 20", openId).Scan(&count)
	return
}

func (u *inviteListServer) GetInvited(openid string) (info []InviteInfo) {
	rows, err := Db.Query("SELECT users.name, users.head_img, users.icon FROM `invite_list` INNER JOIN users ON invite_list.invite_openid = users.unique_id WHERE invite_list.open_id = ? ORDER BY users.icon DESC LIMIT 3", openid)
	if err == nil {
		for rows.Next() {
			var Friend InviteInfo
			err = rows.Scan(&Friend.Name, &Friend.Avatar, &Friend.Balance)
			if err != nil {
				return
			}

			info = append(info, Friend)
		}
	}

	return
}

func (u *inviteListServer) GetInvited2(openid string) (info []InviteInfoImg) {
	rows, err := Db.Query("SELECT users.head_img FROM `invite_list` INNER JOIN users ON invite_list.invite_openid = users.unique_id WHERE invite_list.open_id = ? ORDER BY invite_list.time ASC LIMIT 10", openid)
	if err == nil {
		for rows.Next() {
			var Friend InviteInfoImg
			err = rows.Scan(&Friend.Avatar)
			if err != nil {
				return
			}

			info = append(info, Friend)
		}
	}

	return
}
